﻿using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Xml;
using Blog.Infrastructure.DataAcces.Repositories.Abstractisations;
using Blog.Presentation.StructureMap;

namespace Blog.Presentation.Sindication
{
    public class Feeds : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var isAtom = context.Request.QueryString.ToString().Contains("atom");

            var feed = CreateFeed(isAtom);

            using (var xtw = new XmlTextWriter(context.Response.OutputStream, Encoding.UTF8))
            {
                feed.WriteTo(xtw);
            }
        }

        public bool IsReusable
        {
            get { return false; }
        }


        public SyndicationFeedFormatter CreateFeed(bool res)
        {

            var feed = new SyndicationFeed("Feed Title", "Voutrin's posts", null) { Items = GetItems() };

            SyndicationFeedFormatter formatter = null;

            if (res)
            {
                formatter = new Atom10FeedFormatter(feed);
            }
            else
            {
                formatter = new Rss20FeedFormatter(feed);
            }

            return formatter;
        }

        private IEnumerable<SyndicationItem> GetItems()
        {
            var articles = IoC.Resolve<IArticleRepository>().GetAll();

            return (from article in articles
                    select new SyndicationItem(article.Title, article.Content, null)).ToList();

        }

    }
}